package com.example.xlmkotlinwanandroid.model.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.xlmkotlinwanandroid.base.BaseViewModel
import com.example.xlmkotlinwanandroid.data.Resource
import com.example.xlmkotlinwanandroid.model.repository.Repository
import com.example.xlmkotlinwanandroid.model.bean.ArticleBean
import com.example.xlmkotlinwanandroid.model.bean.BannerBean
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.lang.Exception

class HomeViewModel : BaseViewModel() {

    //页码 首页数据页码从0开始
    private var pageNo = 0

    //viewModel中文章的可观察对象
    private var homeLiveData = MutableLiveData<List<ArticleBean>>()
    private var bannerLiveData = MutableLiveData<Resource<ArrayList<BannerBean>>>()
    val bannerObservableData: MutableLiveData<Resource<ArrayList<BannerBean>>> get() = bannerLiveData

    lateinit var bannerData: List<BannerBean>
    fun getHomeLiveData(isRefresh: Boolean): MutableLiveData<List<ArticleBean>> {
        if (isRefresh) {
            pageNo = 0
        }
        viewModelScope.launch {
            //必须要加上try-catch,否则网络错误的时候APP会崩溃
            try {
                val articles = Repository.getHomeViewModel(pageNo)
                articles?.let {
                    pageNo++
                    homeLiveData.postValue(it)
                }
            } catch (e: Exception) {

            }
        }
        return homeLiveData
    }

    //把轮播图发出去
    fun getMyBannerLiveData() {
        bannerLiveData.value = Resource.Loading()
        viewModelScope.launch {
            remoteRepository.getBanners().collect {
                bannerLiveData.value = it
            }

        }
    }
}
